package org.cloudie.docs.editor.client.managers;

import java.util.ArrayList;

import org.cloudie.docs.editor.client.behaviors.HasContextMenuBehavior;
import org.cloudie.docs.editor.client.widgets.AdvancedPanel;
import org.cloudie.docs.editor.client.widgets.ContextMenu;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.ContextMenuEvent;
import com.google.gwt.event.dom.client.ContextMenuHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;

public class ContextMenuManager
      implements ContextMenuHandler, ClickHandler {

  private AdvancedPanel boundaryPanel;
  private ContextMenu defaultContextMenu;
  private ContextMenu activeContextMenu;
  private ArrayList<ContextMenu> contextMenus;
  
  public ContextMenuManager(AdvancedPanel boundaryPanel,
        ContextMenu defaultContextMenu) {
    this.boundaryPanel = boundaryPanel;
    this.boundaryPanel.addContextMenuHandler(this);
    this.boundaryPanel.addClickHandler(this);
    this.defaultContextMenu = defaultContextMenu;
    this.contextMenus = new ArrayList<ContextMenu>();
  }
  
  private void activateMenu(ContextMenu menu, int x, int y) {
	if (menu == activeContextMenu) {
      boundaryPanel.setWidgetPosition(activeContextMenu, x, y);
	  return;
	}
    deactivateMenu();
    activeContextMenu = menu;
    if (activeContextMenu.isAttached() &&
      activeContextMenu.getParent() == boundaryPanel) {
      boundaryPanel.setWidgetPosition(activeContextMenu, x, y);
    } else {
      boundaryPanel.add(activeContextMenu, x, y);
      activeContextMenu.getElement().getStyle().setZIndex(100);
    }
    activeContextMenu.show();
  }
  
  private void deactivateMenu() {
    if (activeContextMenu != null) {
	  activeContextMenu.hide();
	  activeContextMenu = null;
	}
  }

  @Override
  public void onContextMenu(ContextMenuEvent event) {
    int x = DOM.eventGetClientX((Event) event.getNativeEvent()) - boundaryPanel.getAbsoluteLeft();
    int y = DOM.eventGetClientY((Event) event.getNativeEvent()) - boundaryPanel.getAbsoluteTop();
    ContextMenu menu = null;
    if (event.getSource() == boundaryPanel) {
      menu = defaultContextMenu;
    } else if (event.getSource() instanceof HasContextMenuBehavior) {
      menu = ((HasContextMenuBehavior) event.getSource()).getContextMenu();
    }
    if (menu != null) {
      if (!contextMenus.contains(menu)) {
        contextMenus.add(menu);
      }
      activateMenu(menu, x, y);
    }
  }

  @Override
  public void onClick(ClickEvent event) {
    deactivateMenu();
  }
  
}
